<?php
/**
 * Http Test Page
 *
 * For use with web/client functional tests. It is expected by those tests that
 * your local development server will be configured to serve this at url
 * http://localhost/test/http.php
 *
 * 301, 302 requests will redirect to 200 page
 *
 * An infinite redirect loop can be requested with query string '&loop=1'
 * appended
 *
 */

/**
 * default settings
 */
$http_status = 200;
$PostDict = array();

/**
 * valid http status list
 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
 */
$ValidHttpStatus = array(
    200 => 'OK',
    301 => 'Moved Permanently',
    302 => 'Found',
    403 => 'Forbidden',
    404 => 'Not Found',
    500 => 'Internal Server Error'
);
$ValidHttpCodes = array_keys($ValidHttpStatus);

/**
 * set http status header
 */
if ( isset($_GET['status']) && in_array($_GET['status'], $ValidHttpCodes) ) {
    $http_status = $_GET['status'];
}
$header = sprintf('%s %s %s', $_SERVER['SERVER_PROTOCOL'], $http_status,
                  $ValidHttpStatus[$http_status]);
header($header);

/**
 * check for post values
 */
if ( ! empty($_POST) ) {
    $PostDict = $_POST;
}

/**
 * set cookies
 */
foreach ( $PostDict as $key => $value ) {
    if ( strpos($key, 'cookie') !== FALSE ) {
        setcookie($key, $value, time()+300);
    }
}


/**
 * redirect codes
 */
if ( in_array($http_status, array(301,302)) ) {
    $new_status = 200;
    $url_f = 'http%s://%s%s?status=%s';

    if ( isset($_GET['loop']) && $_GET['loop'] ) {
        $new_status = $http_status;
        $url_f = 'http%s://%s%s?status=%s&loop=1';
    }

    $https = ( $_SERVER['HTTPS'] == 'on' ) ? 's' : '';
    $redirect_url = sprintf($url_f, $https, $_SERVER['SERVER_NAME'],
                            $_SERVER['PHP_SELF'], $new_status);
    header(sprintf('Phpwell-Redirect: %s', $redirect_url));
    header(sprintf('Location: %s', $redirect_url));
}

/**
 * headers
 */
header('Phpwell: http://code.google.com/p/klenwell/');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTTP Status: <?php echo $http_status; ?></title>
    </head>

    <body>
        <h2>HTTP Status: <?php echo $http_status; ?></h2>
    </body>

    <!-- Display post values if sent -->
    <?php if ( ! empty($PostDict) ): ?>
    <pre><?php print_r($PostDict); ?></pre>
    <?php endif; ?>

</html>
